<template>
  <div>
    <!-- <div class="n-layout-page-header">
      <n-card :bordered="false" title="用户模块">
         这是由系统生成的CURD表格，你可以将此行注释改为表格的描述
      </n-card>
    </div> -->
    <n-card :bordered="false" class="proCard" title="用户模块">
      <BasicForm  ref="searchFormRef" @register="register" @submit="reloadTable" @reset="reloadTable" @keyup.enter="reloadTable">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>
      <BasicTable  ref="actionRef"  :columns="columns" :request="loadDataTable" :row-key="(row) => row.id" :actionColumn="actionColumn" :scroll-x="scrollX" :resizeHeightOffset="-10000" >
        <template #tableTitle></template>
      </BasicTable>
    </n-card>

    <n-modal
     :mask-closable="false" :show-icon="false" preset="dialog"
      v-model:show="showModal"
      title="收货地址"
      :style="{width: '1200px'}"
    >
      <ReceiverAddress :userId="userId" />
      <template #action>
        <n-space>
          <n-button @click="showModal = false">
            关闭
          </n-button>
        </n-space>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { List, OpenMember, Qrcode, QueryOldTicket, Status } from '@/api/userModule';
import { BasicForm, useForm } from '@/components/Form/index';
import { BasicTable, TableAction } from '@/components/Table';
import { usePermission } from '@/hooks/web/usePermission';
import { useDictStore } from '@/store/modules/dict';
import { renderIcon } from '@/utils';
import { adaModalWidth, adaTableScrollX } from '@/utils/hotgo';
import ReceiverAddress from '@/views/receiverAddress/index.vue';
import { CrownOutlined, EnvironmentOutlined, LockOutlined, QrcodeOutlined, TagOutlined, UnlockOutlined } from '@vicons/antd';
import { NImage, NSpin, useDialog, useMessage } from 'naive-ui';
import { computed, h, onMounted, reactive, ref } from 'vue';
import { columns, loadOptions, schemas, State } from './model';


  const dict = useDictStore();
  const dialog = useDialog();
  const message = useMessage();
  const { hasPermission } = usePermission();
  const actionRef = ref();
  const searchFormRef = ref<any>({});
  const editRef = ref();
  const showModal = ref(false);
  const dialogWidth = computed(() => {
    return adaModalWidth(840);
  });
  const userId = ref();

  const actionColumn = reactive({
    width: 100,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record: State) {
      return h(TableAction as any, {
        style: 'button',
        dropDownActions: [
          {
            label: '查券数',
            key: 'handleQueryOldSystemCoupon',
            ifShow: () => {
              return [210, 211, 212].includes(record.roleId);
            },
            auth: ['/operation/queryOldTicket'],
            type: 'primary',
            icon: renderIcon(TagOutlined),
          },
          {
            label: '开会员',
            key: 'openMember',
            ifShow: () => {
              return [210, 211, 212].includes(record.roleId);
            },
            auth: ['/operation/openMember'],
            type: 'primary',
            icon: renderIcon(CrownOutlined),
          },
          {
            label: '二维码',
            onClick: handleQrcode.bind(null, record),
            key: 'qrcode',
            ifShow: () => {
              return [210, 211, 212].includes(record.roleId);
            },
            auth: ['/miniProgram/qrCode'],
            type: 'primary',
            icon: renderIcon(QrcodeOutlined)
          },
          {
            label: '收货地址',
            onClick: handleAddress.bind(null, record),
            key: 'address',
            ifShow: () => {
              return [210, 211, 212].includes(record.roleId);
            },
            // auth: ['/userModule/address'],
            type: 'primary',
            icon: renderIcon(EnvironmentOutlined),
          },
          {
            label: '冻结',
            onClick: handleStatus.bind(null, record, 2),
            key: 'status2',
            ifShow: () => {
              return record.status === 1;
            },
            auth: ['/userModule/status'],
            type: 'default',
            icon: renderIcon(LockOutlined),
          },
          {
            label: '解冻',
            onClick: handleStatus.bind(null, record, 1),
            key: 'status1',
            ifShow: () => {
              return record.status === 2;
            },
            auth: ['/userModule/status'],
            type: 'success',
            icon: renderIcon(UnlockOutlined),
          },
        ],
        select: (key) => {
          switch (key) {
            case 'status1':
            case 'status2':
              handleStatus(record, key === 'status1' ? 1 : 2);
              break;
            case 'openMember':
              handleOpenMember(record);
              break;
            case 'handleQueryOldSystemCoupon':
              handleQueryOldSystemCoupon(record);
              break;
            case 'qrcode':
              handleQrcode(record);
              break;
            case 'address':
              handleAddress(record);
              break;
          }
        }
      });
    },
  });

  const scrollX = computed(() => {
    return adaTableScrollX(columns, actionColumn.width);
  });

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  // 加载表格数据
  const loadDataTable = async (res) => {
    return await List({ ...searchFormRef.value?.formModel, ...res });
  };

  // 重新加载表格数据
  function reloadTable() {
    actionRef.value?.reload();
  }

  // 修改状态
  function handleStatus(record: Recordable, status: number) {
    Status({ id: record.id, status: status }).then((_res) => {
      message.success((status === 1? '解冻' : '冻结') + '成功');
      setTimeout(() => {
        reloadTable();
      });
    });
  }

  // 查询旧系统券数
  function handleQueryOldSystemCoupon(record: Recordable) {
    QueryOldTicket({ id: record.id }).then((_res) => {
      dialog.success({
        title: '查询旧系统券数',
        content: () => h('div', {}, [
          h('div', { depth: 3 }, { default: () => "至尊免单券：" + _res.specialTicket }),
          h('div', { depth: 3 }, { default: () => "普通免单券：" + _res.generalTicket }),
        ]),
        negativeText: '关闭',
      });
    });
   
  }

  // 开通会员
  function handleOpenMember (record: Recordable) {
    dialog.warning({
      title: '开通月卡会员',
      content: '点击确认，开通月卡会员',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        OpenMember({ id: record.id }).then((_res) => {
          message.success('开通成功');
          setTimeout(() => {
            reloadTable();
          });
        });
      },
    });
  }

  // 二维码
  function handleQrcode(record: Recordable) {
  let url = '';
  let loadingDia = true;

  // 先弹窗，显示加载状态
  const dialogInstance = dialog.success({
    loading: loadingDia,
    title: record.nickname + '-分享绑定二维码',
    content: () => h(
      NSpin,
      {
        style: 'text-align: center; padding: 180px;',
      },
    ),
  });

  Qrcode({
    path: "pages/index/index",
    scene: "invite_code=" + record.inviteCode,
    isHyaline: false,
    type: 0,
  }).then((_res) => {
    if (_res?.qrCodeUrl) {
      // 更新弹窗内容，显示图片
      dialogInstance.content = () => h(
          NImage,
          {
            src: "https://imgs.ynz666.com/" + _res.qrCodeUrl,
            alt: '小程序二维码',
            width: 400,
            previewDisabled: true,
          }
        )
    } else {
      message.error('生成失败');
      dialogInstance.destroy(); // 关闭弹窗
    }
  }).catch((_err) => {
    message.error('生成失败');
    dialogInstance.destroy(); // 关闭弹窗
  });
}

  function handleAddress (record: Recordable) {
    userId.value = record.id;
    showModal.value = true;
  }
  onMounted(() => {
    loadOptions();
  });
</script>

<style lang="less" scoped></style>